// 小端转换
function littleEndian(str) {
	const len = str ? str.length : 0
	if (len > 2) {
		let newStr = ''
		for (let k = len - 2; k >= 0; k = k - 2) {
			newStr += str.substr(k, 2)
		}
		return newStr
	}
	return str
}

// 时间判断
function getNewDate(value) {
	if (value) {
		if (value instanceof Date) {
			return value
		} else if (typeof value === 'string' && isNaN(value)) {
			return new Date(value.replace(/-/g, '/'))
		}
		return new Date(value)
	}
	return new Date()
}

let util = {
	getNewDate: getNewDate,
	/** 小端转换 (hex => str) F => 15 **/
	littleParseInt: function (string) {
		const str = littleEndian(string)
		return parseInt(str, 16)
	},

	/** 小端转换 (str => hex) 15 => F **/
	littleToString: function (string, uint = 8) {
		const str = string.toString(16).toUpperCase()
		let value = littleEndian(str)
		let length = value.length
		if (length % 2 > 0) {
			value = '0' + value
			length++
		}
		if (uint === 16 && length !== 4) {
			const Val = value + '0000'
			value = Val.substr(0, 4)
		} else if (uint === 32 && length !== 8) {
			const Val = value + '00000000'
			value = Val.substr(0, 8)
		}
		return value
	}

}

// ArrayBuffer转16进度字符串示例
util.ab2hex = function (buffer) {
	const hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function (bit) {
			return ('00' + bit.toString(16)).slice(-2)
		}
	)
	return hexArr.join('')
}

/** 2位补齐0 **/
util.bitsMakeUp = function (value) {
	let str = value
	if (!value) str = '00'
	else if (value < 9 || value.length === 1) {
		str = '0' + value
	}
	return str
}

/** 字符转以函数 **/
util.stringToJson = function (resData) {
	if (typeof (resData) == 'string') {
		try {
			return JSON.parse(resData)
		} catch (error) {
			var dataStr = resData.replace(/:"{/g, ':{')
			dataStr = dataStr.replace(/}",/g, '},')
			dataStr = dataStr.replace(/}"}/g, '}}')
			dataStr = dataStr.replace(/\\/g, '')
			return JSON.parse(dataStr)
		}
	}

	return resData;
}

/** 十六进制字符串 => 协议数组 **/
util.getAttrStringToArray = function (string) {
	var newStr = string.toUpperCase()
	var length = newStr.length;
	var i = 0;
	var arr = []
	do {
		var start = newStr.substr(i, 2)
		var lg = parseInt(start, 16)
		var slg = lg * 2
		var str = newStr.substr(i, slg)
		length = length - slg
		i += slg
		arr.push(str)
	} while (length > 0)

	return arr
}

/** UTC时间，格式：yyyyMMddTHHmmssZ，24小时制 type:start/end **/
util.getUTCTime = function (value, type) {
	const date = getNewDate(value)
	const makeUp = function (val) {
		if (val < 10) val = '0' + val
		return val.toString()
	}
	let YY = date.getFullYear()
	if (YY < 1900) YY = YY + 1900
	const MM = makeUp(date.getMonth() + 1)
	const DD = makeUp(date.getDate())
	let ZZ = ''
	if (type === 'start') {
		ZZ = '000001'
	} else if (type === 'end') {
		ZZ = '235959'
	} else {
		ZZ = makeUp(date.getHours()) + makeUp(date.getMinutes()) + makeUp(date.getSeconds())
	}
	return YY + MM + DD + 'T' + ZZ + 'Z'
}

/** 获取时间的秒数 **/
util.getTimeSeconds = function (value) {
	return Math.floor(getNewDate(value).getTime() / 1000)
}

/** 字符串转16进制 **/
util.stringToHexCharCode = function (str) {
	if (!str) return ''
	let hexArr = []
	for (let i = 0, len = str.length; i < len; i++) {
		hexArr.push(str.charCodeAt(i).toString(16))
	}
	return hexArr.join('')
}

/** 16进制转字符串 **/
util.hexCharCodeToString = function (hexChar) {
	const len = hexChar.length
	if (len % 2 !== 0) {
		return ''
	}
	let a
	let resultStr = []
	for (let i = 0; i < len; i = i + 2) {
		a = parseInt(hexChar.substr(i, 2), 16)
		resultStr.push(String.fromCharCode(a))
	}
	return resultStr.join('')
}

/** ArrayBuffer转16进制字符串 **/
util.arrayBufferToHex = function (buffer) {
	return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}

/** 分数3等级 颜色 **/
util.getScoreGradeColor = function (score) {
	if (score > 80) return '#47CC47'
	else if (score > 60) return '#00AAEE'
	return '#FF7500'
}

/** 错误码解析函数 **/
util.getErrorCode = function (errCode) {
	let str = ''
	if (!errCode || errCode === 0 || errCode === 200) {
		errCode = 0
		str = '设置成功'
	} else {
		switch (errCode) {
			case 0:
				str = '打开蓝牙成功';
				break
			case 10:
				str = '设备响应超时，请求没有响应 ';
				break
			case 11:
				str = '设备已离线';
				break
			case 12:
				str = '备数据参数校验非法，在设备控制参数校验失败时，返回APP或者云端';
				break
			case 10000:
				str = '未初始化蓝牙适配器(not init)';
				break
			case 10001:
				str = '当前蓝牙适配器不可用(not available)';
				break
			case 10002:
				str = '没有找到指定设备(no device)';
				break
			case 10003:
				str = '连接失败(connection fail)';
				break
			case 10004:
				str = '没有找到指定服务(no service)';
				break
			case 10005:
				str = '	没有找到指定特征值(no characteristic)';
				break
			case 10006:
				str = '	当前连接已断开(no connection)';
				break
			case 10007:
				str = '当前特征值不支持此操作(property not support)';
				break
			case 10008:
				str = '其余所有系统上报的异常(system error)';
				break
			case 10009:
				str = 'Android 系统特有，系统版本低于 4.3 不支持 BLE(system not support)';
				break
			case 2000:
				str = '数据存储失败';
				break
			case 2001:
				str = '数据存储成功';
				break
			case 90001:
				str = '内部错误/系统错误';
				break
			case 90002:
				str = 'DATA数据过大或过小';
				break
			case 90003:
				str = '同账号下，存储空间已用完';
				break
			case 90004:
				str = '系统存储空间不足';
				break
			case 90005:
				str = '函数在错误的场景被调用；或存在前后依赖的接口，在前述接口未调用前，调动该接口';
				break
			case 90006:
				str = '设备在云端注册失败';
				break
			case 90007:
				str = '输入的hilink设备Id错误';
				break
			case 90008:
				str = '输入的数据格式错误';
				break
			case 90009:
				str = '连接BLE蓝牙设备失败';
				break
			case 90010:
				str = '断开BLE蓝牙设备失败';
				break
			case 90011:
				str = '文件下载失败';
				break
			case 90012:
				str = '设备重复了';
				break
			default:
				break
		}
	}
	return {
		errCode: errCode,
		errMsg: str
	}
}

module.exports = util
